package com.highper.gateway.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.highper.common.entity.po.application.AppUser;
import com.highper.common.entity.vo.LoginVo;
import com.highper.common.globalization.Globalization;
import com.highper.common.mapper.AuthMapper;
import com.highper.common.sehcma.ContextHandler;
import com.highper.gateway.service.IAuthService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import static com.highper.common.constant.SchemaConstant.HIGHPER_APPLICATION;

/**
 * @Author ZhangGJ
 * @Date 2022/01/25 09:34
 */
@Service
public class AuthServiceImpl extends ServiceImpl<AuthMapper, AppUser> implements IAuthService {

    @Override
    public String login(LoginVo loginVo) {
        ContextHandler.setSchema(HIGHPER_APPLICATION);
        AppUser appUser = this.baseMapper.selectOne(
                new LambdaQueryWrapper<AppUser>().eq(AppUser::getUsername, loginVo.getUsername()));
        if (appUser == null) {
            throw new RuntimeException(Globalization.languageWebFlux("user-not-exist"));
        }
        String md5 = SaSecureUtil.md5(loginVo.getPassword());
        if (!md5.equals(appUser.getPassword())) {
            throw new RuntimeException(Globalization.languageWebFlux("password-error"));
        }
        StpUtil.login(appUser.getUserId());
        StpUtil.getSession().set("user", appUser);
        return StpUtil.getTokenValue();
    }

    @Override
    public boolean logout() {
        StpUtil.logout();
        return true;
    }

    @Override
    public Map<String, Boolean> loginStatus() {
        Map<String, Boolean> map = new HashMap<>(4);
        map.put("loginStatus", StpUtil.isLogin());
        return map;
    }

    @Override
    public SaTokenInfo tokenInfo() {
        return StpUtil.getTokenInfo();
    }

}
